import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() {
  runApp(const MaterialApp(home: HomePage()));
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> list = [
    '第 1 条数据',
    '第 2 条数据',
  ];
  var globalKey = GlobalKey<AnimatedListState>();
  bool flag = false; // 防止删除太快
  Widget _buildItem(index) {
    return ListTile(
      trailing: IconButton(
        icon: const Icon(Icons.delete),
        onPressed: () {
          setState(() {
            if (flag) return;
            flag = true;
            var removeItem = _buildItem(index);
            list.removeAt(index);
            // 删除动画，传入删除元素
            globalKey.currentState!.removeItem(index, (context, animation) {
              // 返回动画，这里使用ScaleTransition来包裹
              return ScaleTransition(
                scale: animation,
                child: removeItem,
              );
            });
            Timer.periodic(Duration(milliseconds: 500), (timer) {
              flag = false;
              timer.cancel();
            });
          });
        },
      ),
      title: Text(list[index]),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('你好flutter1'),
        ),
        // 动画列表
        body: AnimatedList(
          key: globalKey,
          initialItemCount: list.length,
          itemBuilder: (context, index, animation) {
            // 返回动画，这里使用FadeTransition来包裹
            return FadeTransition(
              opacity: animation,
              child: _buildItem(index),
            );
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              list.add('第 ${list.length + 1} 条数据');
              // 新增动画。传入长度
              globalKey.currentState!.insertItem(list.length - 1);
            });
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
